//
//  UITextViewAdditions.m
//  ZhiWeibo
//
//  Created by junmin liu on 10-11-8.
//  Copyright 2010 Openlab. All rights reserved.
//
#import "NSString+Extension.h"
#import "UITextViewAdditions.h"


@implementation UITextView (Addtions)


-(void) insertString:(NSString*)str leftSpace:(BOOL)left rightSpace:(BOOL)right
{
    //str = str.strip;比如@谁，后面必须有空格
    if (str && str.length) {
        
        NSRange selectedRange = [self selectedRange];
        BOOL pagingEnabled = self.pagingEnabled;
        BOOL scrollEnabled = self.scrollEnabled;
        self.pagingEnabled = NO;
        self.scrollEnabled = NO;
        
        NSString* textX = [self text];
        if (selectedRange.location == NSNotFound) {
            selectedRange.location = textX.length; // 定位到最后
            selectedRange.length= 0;
        }
        NSString* texta = selectedRange.location<textX.length+1?[textX substringToIndex:selectedRange.location]: @"";
        NSString* textb = selectedRange.location<textX.length+1?[textX substringFromIndex:selectedRange.location]: @"";
        
        if (left && texta && texta.length) {
            if (![texta hasSuffix:@" "]) {
                str = [NSString stringWithFormat:@" %@", str];
            }
        }
        if (right && textb && textb.length) {
            if (![textb hasPrefix:@" "]) {
                str = [NSString stringWithFormat:@"%@ ", str];
            }
        }
        
        
        NSString* text = [@"" stringByAppendingFormat:@"%@%@%@", texta, str, textb];
    
        self.text = text;
        selectedRange.location += str.length;
        
        self.pagingEnabled = pagingEnabled;
        self.scrollEnabled = scrollEnabled;
        self.selectedRange = selectedRange;
    }
    [self resignFirstResponder]; // 非常重要，让它支持 重新获取 光标位置
}

- (void) insertString: (NSString *) insertingString  
{  
    NSRange range = self.selectedRange;  
    NSString * firstHalfString = [self.text substringToIndex:range.location];  
    NSString * secondHalfString = [self.text substringFromIndex: range.location + range.length];  
    //self.scrollEnabled = NO;  // turn off scrolling or you'll get dizzy ... I promise  
    BOOL pagingEnabled = self.pagingEnabled;
    BOOL scrollEnabled = self.scrollEnabled;
    self.pagingEnabled = NO;
    self.scrollEnabled = NO;
	
    self.text = [NSString stringWithFormat: @"%@%@%@",  
					 firstHalfString,  
					 insertingString,  
					 secondHalfString];  
    //range.length = [insertingString length];  
    range.location = range.location + [insertingString length];
	range.length = 0;
	//self.scrollEnabled = YES;  // turn scrolling back on.  
    self.pagingEnabled = pagingEnabled;
    self.scrollEnabled = scrollEnabled;
    self.selectedRange = range;  
    
    [self resignFirstResponder]; // 非常重要，让它支持 重新获取 光标位置
}

@end
